/***************************************************************************
 *   Copyright (C) 2007 by gaojian   *
 *   gaojian2008cnn@126.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "translatedialog.h"
#include "vocabularylist.h"
#include "dictionary.h"
#include "settings.h"
#include "preferencesdialog.h"
#include "floatwin.h"

#include <khtml_part.h>
#include <khtmlview.h>
#include <klocale.h>
#include <kcombobox.h>
#include <kurl.h>
#include <ksystemtray.h>//系统托盘图标类
#include <kpopupmenu.h>
#include <kaction.h>
#include <kapp.h>
#include <kstandarddirs.h>
#include <kiconloader.h>

#include <qlayout.h>
#include <qtextcodec.h>
#include <qsplitter.h>
#include <qpixmap.h>
#include <qcheckbox.h>

///////////////////////////////////
#include <khelpmenu.h>
#include <kiconloader.h>


TranslateDialog::TranslateDialog(QWidget* parent, const char* name) : TranslateDialogBase(parent, name)
{
	// create and add KHTMLPart and display "Welcome" page
	histText->setHistoryItems(kdictsettings.histTextHistory);//读取设置历史列表
	splitter = new QSplitter(this);
	TranslateDialogBaseLayout->addWidget(splitter);
	wordlist = new VocabularyList(splitter);//建立生词列表
	connect( wordlist, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int) ), this, SLOT( mousePressed(int,QListViewItem*,const QPoint&,int) ) );//接收来自生词本的单击事件
	htmlpart = new KHTMLPart(splitter);//建立主控件
	htmlpart->setPluginsEnabled(true);
	connect(htmlpart->browserExtension() ,SIGNAL(openURLRequestDelayed(const KURL&, const KParts::URLArgs&)),this,SLOT(openURLRequest(const KURL &)));

	dict=new Dictionary;//建立字典类
	connect(dict,SIGNAL(searchResult(const QString&)),this,SLOT(showResult(const QString &)));
	connect(dict,SIGNAL(searchError(const QString&)),this,SLOT(showSearchError(const QString &)));
	showWelcome();//显示欢迎页
	preDialog = new PreferencesDialog(kapp->mainWidget());//建立配置对话框
	
	//建立取词窗口
	fetchWordWin = new floatWin();
	connect(fetchWordWin,SIGNAL(fetchResult(const QString&)),this,SLOT(showFetchResultSlot(const QString &)));
	//设置系统托盘 图标
	mytray = new KSystemTray(this,"tray");
	connect(mytray, SIGNAL(quitSelected()), kapp, SLOT(quit ()));//把系统托盘图标的菜单的退出按钮事件直接发送给程序
	KPopupMenu* menu = mytray->contextMenu();
	( new KAction( i18n( "Configure KECDict" ),SmallIcon("configure_shortcuts"), 0, this, SLOT( showConfigureDialog() ), this ) ) ->plug( menu );
	menu->insertSeparator();
	
	fetchWordAction = new KToggleAction(i18n( "Fetch word" ), 0,this, SLOT( fetchWordCheck() ), this );
	fetchWordAction->plug( menu );//选择是否取词
	KHelpMenu* tempMenu =  new KHelpMenu( this, kapp->aboutData(), false );
	KPopupMenu* helpMenu = tempMenu->menu();
	menu->insertItem( i18n( "&Help" ), helpMenu );
	//KSystemTray::loadIcon("filesave.png")
	//QPixmap pixmap;
	//pixmap.load("kecdict");
    KIconLoader * iconLoader = new KIconLoader();
               QPixmap icon = iconLoader->loadIcon( "kecdict", KIcon::Toolbar, 16 );
	mytray->setPixmap(icon);
	//读取取词设置
	fetchWordAction->setChecked(kdictsettings.b_fetchWord);
	checkBox1->setChecked (kdictsettings.b_fetchWord);
	mytray->show();
  
}


TranslateDialog::~TranslateDialog()
{


}


void TranslateDialog::fetchResults()
{
    TranslateDialogBase::fetchResults();
}

void TranslateDialog::textChanged(const QString& arg1)
{
    TranslateDialogBase::textChanged(arg1);
}

void TranslateDialog::translateClicked()
{
    QString text = histText->currentText();
    QTextCodec *codec1 = QTextCodec::codecForName("utf8"); // get the codec for KOI8-R
    text = codec1->fromUnicode( text );//由于currenttext()返回的是Unicode编码字符，所以要把他转换为utf8
    dict->search(text);
    TranslateDialogBase::translateClicked();

}

/*!
    \fn TranslateDialog::showResult(const QString &html)
 */
void TranslateDialog::showResult(const QString &html)
{
	htmlpart->begin();
	htmlpart->write(i18n(html));
	htmlpart->end();
}


/*!
    \fn TranslateDialog::showSearchError()
 */
void TranslateDialog::showSearchError(const QString &html)
{
	htmlpart->begin();
	htmlpart->write(i18n(html));
	htmlpart->end();
}

/*!
    \fn TranslateDialog::openURLRequest(const KURL &url, const KParts::URLArgs & )
 */
void TranslateDialog::openURLRequest(const KURL &url )
{
    htmlpart->openURL(url.url());
}

/*!
    \fn TranslateDialog::mousePressed(int button, QListViewItem *i, const QPoint &, int)
 */
void TranslateDialog::mousePressed(int button, QListViewItem *i, const QPoint &, int)
{
    if ( button == Qt::LeftButton )
	{
		if(0!=i)
		{
			qDebug("rightButtonPressed");
			dict->search(i->text(1));//搜索生词列表中被单击的单词
		}
	}
}


/*!
    \fn TranslateDialog::showWelcome()
 */
void TranslateDialog::showWelcome()
{
	QString welcome="<body   style=\"overflow:hidden\">";
	welcome+="<div style=\"position: absolute; left: 1px; top: 1px; width: 100%; height: 100%;\">";
	welcome+="<table  height=\"100%\" width=\"100%\">";
	welcome+="<tr>";
	welcome+="<td valign=\"middle\"><span id=\"dict_daily\">";
	welcome+="<a href=\"http://dict.cn/\" target=\"_blank\">Dict.CN 在线词典, 英语学习, 在线翻译</a>";
	welcome+="</span>";
	welcome+="<script language=\"JavaScript\" src=\"http://dict.cn/daily.php\" defer=\"defer\">";
	welcome+="</script>";
	welcome+="</td>";
	welcome+="</tr>";
	welcome+="<tr>";
	welcome+="<td align=\"center\" valign=\"middle\"><img src=\"http://s8.album.sina.com.cn/pic_3/4c8e50c5020014jv\" alt=\"\" width=\"275\" height=\"165\" /></td>";
	welcome+="</tr>";
	welcome+="<tr>";
	welcome+="<td height=\"49\" >&nbsp;</td>";
	welcome+="</tr>";
	welcome+="</table>";
	welcome+="</div>";
	welcome+="</body>";
	showResult(welcome);
}


/*!
    \fn TranslateDialog::showConfigureDialog()
 */
void TranslateDialog::showConfigureDialog()
{
    preDialog->show();
}


/*!
    \fn TranslateDialog::closeEvent ( QCloseEvent * e )
 */
void TranslateDialog::closeEvent ( QCloseEvent * e )
{//做这一步是为了在窗口隐藏之前保存查词的历史记录
   kdictsettings.histTextHistory=histText->historyItems();
   kdictsettings.save();
   hide();
}

//这是主窗口中的取词选项发送的信号
void TranslateDialog::fetchWordClicked(bool on)
{
fetchWordAction->setChecked(checkBox1->isChecked () );
fetchWord(checkBox1->isChecked ());
}
//这是系统托盘菜单中取词选项发送的信号
void TranslateDialog::fetchWordCheck()
{
checkBox1->setChecked(fetchWordAction->isChecked());//这会使车参考checkBox1发送fetchWordClicked信号
}

/*!
    \fn TranslateDialog::fetchWord(bool fetch)
 */
void TranslateDialog::fetchWord(bool fetch)
{
	kdictsettings.b_fetchWord = fetch;
	if( fetch )
	{
	fetchWordWin->startFetchWord();
	}else{
	fetchWordWin->stopFetchWord();
	}
}


/*!
    \fn TranslateDialog::showFetchResultSlot(const QString &)
 */
void TranslateDialog::showFetchResultSlot(const QString &word)
{
	//由于从取词窗口传送过来的词编码是unicode所以要先把他转换为utf8
	QString str;
	QTextCodec *codec1 = QTextCodec::codecForName("utf8"); // 把Unicode编码转换为utf8编码
	str = codec1->fromUnicode( word);
	dict->search(word);
	show ();
}
